package com.lugea.common.json;

import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.Lists;

/**
 * @author enluw
 * @date 2020-01-27
 * @描述 序列化工具
 */
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        JsonUtils.objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        JsonUtils.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonUtils.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        List<Module> modules = Lists.newArrayList();
        SimpleModule localData = new SimpleModule("LocalDataModule", Version.unknownVersion());
        localData.addSerializer(LocalDate.class, new LocalDateStdScalarSerializer());
        localData.addDeserializer(LocalDate.class, new LocalDateStdScalarDeserializer());
        modules.add(localData);
        SimpleModule dateTimeModule = new SimpleModule("DateTimeModule", Version.unknownVersion());
        dateTimeModule.addDeserializer(DateTime.class, new DateTimeStdScalarDeserializer());
        dateTimeModule.addSerializer(DateTime.class, new DateTimeStdScalarSerializer());
        modules.add(dateTimeModule);
        JsonUtils.objectMapper.registerModules(modules);
    }

    public static ObjectMapper getObjectMapperInstance() {
        return JsonUtils.objectMapper;
    }

}
